import * as THREE from "three";
import * as d3 from "d3";
import {TextGeometry} from "three/addons/geometries/TextGeometry.js";
import {FontLoader} from 'three/addons/loaders/FontLoader.js';
import borderMap from '../components/constant/boundary.json'

let handleProject
const loader = new FontLoader();
export const handleData = (jsonData, scene, center, scale = 1000, level = 0) => {
    loader.load('examples/fonts/font.json', (font) => {
        handleProject = d3.geoMercator().center(center).scale(scale).translate([0, 0])
        // 存储地图容器
        const mapContainer = new THREE.Object3D()
        const featureList = jsonData.features;
        featureList.forEach((feature) => {
            // 创建市的容器
            const city = new THREE.Object3D;
            // 省份名称
            city.properties = feature.properties.name
            city.name = feature.properties.name // 省份名称
            mapContainer.name = feature.properties.name // 省份名称

            // 省份坐标信息
            const coordinates = feature.geometry.coordinates

            if (feature.geometry.type === 'MultiPolygon') {
                coordinates.forEach((cord) => {
                    // coordinate 就是边界素组坐标系
                    cord.forEach((coordinate) => {
                        // 三维多边形
                        const extrudeMesh = creatDepthPolygon(coordinate)
                        // 给extrudeMesh对象加一个自定义的属性（properties）用来存放省份名称
                        extrudeMesh.properties = feature.properties.name
                        // 绘制省份边缘线条
                        const line = createLine(coordinate);
                        line.properties = feature.properties.name
                        // 绘制省份柱体数据
                        const extrudeMeshCylinder = createCylinder(feature, level)
                        // 添加省份文字信息
                        const text = createText(feature, level, font)
                        // 将面加入3d 中
                        city.add(extrudeMesh)
                        // 将线加入3d 中
                        city.add(line)
                        // 将柱体加入3d 中
                        if (extrudeMeshCylinder) {
                            city.add(extrudeMeshCylinder)
                        }
                        // // 将文字加入3d 中
                        if (text) {
                            city.add(text)
                        }
                    })
                })
            }
            if (feature.geometry.type === 'Polygon') {
                coordinates.forEach((coordinate) => {
                    // 三维多边形
                    const extrudeMesh = creatDepthPolygon(coordinate)
                    extrudeMesh.properties = feature.properties.name
                    // 线条
                    const line = createLine(coordinate);
                    line.properties = feature.properties.name
                    // 绘制省份柱体数据
                    const extrudeMeshCylinder = createCylinder(feature, level)
                    // // 添加省份文字信息
                    const text = createText(feature, level, font)
                    city.add(extrudeMesh)
                    city.add(line)
                    // 将柱体加入3d 中
                    if (extrudeMeshCylinder) {
                        city.add(extrudeMeshCylinder)
                    }
                    // // 将文字加入3d 中
                    if (text) {
                        city.add(text)
                    }
                })
            }
            // 将每个省份的容器加入到地图容器中
            mapContainer.add(city)
        })
        // 将地图容器加入到场景中
        scene.add(mapContainer)
    })
}
function createText(feature, level, font) {
    if (feature.properties.name) {
        const [x_XYZ, y_XYZ] = handleProject(feature.properties.center)
        // 缺点：首次渲染很慢 无法使用中文已经中文标点符号 需要特殊处理（自行百度）
        // 优点：清晰
        const geometry = new TextGeometry(`GDP:32632`, {
            font: font,
            size: !level ? 10 : 6, // 字体大小
            depth: 0,
            curveSegments: 4,
        });
        const materials = new THREE.MeshBasicMaterial({
            color: 0xffffffff,
            transparent: true,
            opacity: 0.5,
        })
        const textMesh = new THREE.Mesh(geometry, materials)
        textMesh.position.set(x_XYZ - 20, -y_XYZ, 150);
        return textMesh

        // // 缺点：使用的是贴图 会导致比较模糊
        // // 优点：首次渲染很快 能使用中文已经中文标点符号
        // const canvas = document.createElement('canvas');
        // const context = canvas.getContext('2d');
        // // 设置 Canvas 的尺寸
        // canvas.width = 512;
        // canvas.height = 256;
        //
        // // 设置字体样式
        // context.font = '50px Arial';
        // context.fillStyle = 'white';  // 设置文字颜色
        // context.textAlign = 'center'; // 文字居中
        // context.textBaseline = 'middle'; // 文字垂直居中
        // // 绘制文字到 Canvas 中心
        // context.fillText('GDP 总额：20000亿', canvas.width / 2, canvas.height / 2);
        //
        // const texture = new THREE.CanvasTexture(canvas);
        // const material = new THREE.MeshBasicMaterial({ map: texture });
        // const geometry = new THREE.PlaneGeometry(50, 10);
        // const textMesh = new THREE.Mesh(geometry, material);
        // textMesh.position.set(x_XYZ, -y_XYZ, 150);
        // return textMesh
    }
}

function createCylinder(feature, level) {
    const tb = level === 0 ? 10 : 6
    if (feature.properties.center) {
        const [x_XYZ, y_XYZ] = handleProject(feature.properties.center)
        // 随机生成20 - 100 之间的正整数
        const random = Math.floor(Math.random() * 80) + 20
        // 创建一个柱体
        let geometry_g = new THREE.CylinderGeometry(tb, tb, random, 32);
        let material_g = new THREE.MeshBasicMaterial({
            color: '#0DEAF8',
            transparent: true,
            opacity: 0.8
        });
        let cylinder = new THREE.Mesh(geometry_g, material_g);
        cylinder.position.set(x_XYZ, -y_XYZ, 16 + (random / 2));
        cylinder.rotateX(Math.PI / 2);
        return cylinder
    }
    return null
}

// 创建三维多边形(也就是每个省份的地图)
function creatDepthPolygon(coordinate) {
    const shape = new THREE.Shape();
    // 每一个item都是省份边界坐标 需要把 json 的坐标系 转化为d3的坐标系  例如：[117.429915,40.576141]
    coordinate.forEach((item, index) => {
        const [x_XYZ, y_XYZ] = handleProject(item)
        if (index === 0) {
            // moveTo 的主要作用是定义形状的起点位置
            shape.moveTo(x_XYZ, -y_XYZ)
        } else {
            // 依次按照坐标 形成一个多边形
            shape.lineTo(x_XYZ, -y_XYZ)
        }
    })
    const extrudeSettings = {
        steps: 2,
        depth: 16,
        bevelEnabled: true,
        bevelThickness: 1,
        bevelSize: 1,
        bevelOffset: 0,
        bevelSegments: 1
    };
    // ExtrudeGeometry  创建一个多边形
    const geometry = new THREE.ExtrudeGeometry(shape, extrudeSettings)  //挤压缓冲几何体
    // 设置每个身份的背景颜色
    const material = new THREE.MeshBasicMaterial({
        // color: new THREE.Color(Math.random() * 0xffffff), // 每个省随机赋色
        color: '#d13a34',
        transparent: true,
        opacity: 0.6
    })
    return new THREE.Mesh(geometry, material)
}

// 创建省份边界线条
export function createLine(coordinate, scale) {
    const material = new THREE.LineBasicMaterial({
        color: '#ffffff'
    });
    const points = []
    coordinate.forEach((item) => {
        // 每一个item都是省份边界坐标 需要把 json 的坐标系 转化为d3的坐标系  例如：[117.429915,40.576141]
        const [x_XYZ, y_XYZ] = handleProject(item)
        points.push(new THREE.Vector3(x_XYZ, -y_XYZ, 25))
    })

    const geometry = new THREE.BufferGeometry().setFromPoints(points);

    return new THREE.Line(geometry, material);
}
